package com.yuandian.customer.perception.controller;

import com.yuandian.api.customer_perception.po.AreaMonitorParams;
import com.yuandian.api.customer_perception.vo.AreaOverviewListVo;
import com.yuandian.api.customer_perception.vo.HallOverviewListVo;
import com.yuandian.api.customer_perception.vo.OperatorOverviewListVo;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.customer.perception.service.IAreaMonitorService;
import com.yuandian.utils.YDateUtil;
import com.yuandian.utils.poi.ExcelTitleUtils;
import com.yuandian.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * <p> 地市监控总览请求参数 </p>
 *
 * @Author: LinSheHi
 * @Date: 2021/8/16 10:03
 */
@Slf4j
@Api(value = "地市监控总览接口", tags = "地市监控总览接口")
@RestController
@RequestMapping("/monitor/area")
public class AreaMonitorController {

    @Autowired
    private IAreaMonitorService areaMonitorService;

/*
    @Autowired
    private ISearchOptionService searchOptionService;		TODO 远程调用
*/

    /**
     * 全省概况
     * @param params 请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "地市监控总览-全省概况", notes = "地市监控总览-全省概况")
	@PostMapping("/allAreaOverview")
    public R<Object> queryAllAreaOverview(@RequestBody AreaMonitorParams params) {
        return areaMonitorService.queryAllAreaOverview(params);
    }

    /**
     * 全地市受理量TOP5
     * @param params 请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "地市监控总览-全地市受理量TOP5", notes = "地市监控总览-全地市受理量TOP5")
	@PostMapping("/allAreaCompleteCountTop")
    public R<Object> queryAllAreaCompleteCountTop(@RequestBody AreaMonitorParams params) {
        return areaMonitorService.queryAllAreaCompleteCountTop(params);
    }

    /**
     * 全地市告警量TOP5
     * @param params 请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "地市监控总览-全地市告警量TOP5", notes = "地市监控总览-全地市告警量TOP5")
	@PostMapping("/allAreaAlarmCountTop")
    public R<Object> queryAllAreaAlarmCountTop(@RequestBody AreaMonitorParams params) {
        return areaMonitorService.queryAllAreaAlarmCountTop(params);
    }

    /**
     * 全地市总览列表
     * @param params 请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "地市监控总览-全地市总览列表", notes = "地市监控总览-全地市总览列表")
	@PostMapping("/allAreaOverviewList")
    public R<Object> queryAllAreaOverviewList(@RequestBody AreaMonitorParams params) {
        return areaMonitorService.queryAllAreaOverviewList(params);
    }

    /**
     * 办事处总览列表
     * @param params 请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "地市监控总览-办事处总览列表", notes = "地市监控总览-办事处总览列表")
	@PostMapping("/allHallOverviewList")
    public R<Object> queryAllHallOverviewList(@RequestBody AreaMonitorParams params) {
        return areaMonitorService.queryAllHallOverviewList(params);
    }

    /**
     * 操作员总览列表
     * @param params 请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "地市监控总览-操作员总览列表", notes = "地市监控总览-操作员总览列表")
	@PostMapping("/allOperatorOverviewList")
    public R<Object> queryAllOperatorOverviewList(@RequestBody AreaMonitorParams params) {
        return areaMonitorService.queryAllOperatorOverviewList(params);
    }

    /**
     * 全地市总览列表下载
     *
     * @param params 请求参数
     * @return 全地市总览列表下载
     */
	@ApiOperation(value = "地市监控总览-全地市总览列表下载", notes = "地市监控总览-全地市总览列表下载")
	@ResponseBody
    @PostMapping("/allAreaOverviewListExport")
    public void queryAllAreaOverviewListExport(@RequestBody AreaMonitorParams params, HttpServletResponse response) throws IOException, ParseException {

        List<AreaOverviewListVo> resList = new ArrayList<>();
        try {
            resList = areaMonitorService.queryAllAreaOverviewListExport(params);
        } catch (Exception e) {
            log.error("所选时间表不存在!但表格需要正常导出.");
        }

        String title = "全地市总览列表 ";
        // 文件名
        String fileName = title + System.currentTimeMillis();
        // 表单大标题
        List<String> titleParams = new ArrayList<>();
        titleParams.add(title);
        String formTitleName = ExcelTitleUtils.formTitleName(titleParams,params.getStartTime(),params.getEndTime());

        // 表单大标题合并单元格
        List<List<String>> headList = new ArrayList<>();
        List<String> titleList = Arrays.asList("序号", "地市名称", params.getOfficeName()+"活跃数量", "操作员活跃数量", "系统活跃数量", "业务活跃数量", "访问量", "受理量", "告警访问量", "失败访问量", "成功率", "健康度");
        titleList.forEach(s -> {
            List<String> childHeadList = new ArrayList<>();
            childHeadList.add(formTitleName);
            childHeadList.add(s);
            headList.add(childHeadList);
        });

        // 数据整理加上百分号
        resList.forEach(areaOverviewListVo -> {
            areaOverviewListVo.setSuccessRate(areaOverviewListVo.getSuccessRate() == null ? "" :  (areaOverviewListVo.getSuccessRate() + "%"));
            areaOverviewListVo.setHealthRate(areaOverviewListVo.getHealthRate() == null ? "" :  (areaOverviewListVo.getHealthRate()+ "%"));
        });
        //回退序号
        int index = 1;
        for (AreaOverviewListVo areaOverviewListVo : resList) {
            areaOverviewListVo.setId(index++);
        }
        ExcelUtil.writeExcel(AreaOverviewListVo.class, fileName, title, resList, headList, response);
    }


    /**
     * 办事处总览列表
     * @param params 请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "地市监控总览-办事处总览列表", notes = "地市监控总览-办事处总览列表")
	@ResponseBody
    @PostMapping("/allHallOverviewListExport")
    public void queryAllHallOverviewListExport(@RequestBody AreaMonitorParams params, HttpServletResponse response) throws IOException, ParseException {

        List<HallOverviewListVo> resList = new ArrayList<>();
        try {
            resList = areaMonitorService.queryAllHallOverviewListExport(params);
        } catch (Exception e) {
            log.error("所选时间表不存在!但表格需要正常导出.");
        }

        String title = params.getOfficeName()+"总览列表";
        // 文件名
        String fileName = title + System.currentTimeMillis();

        // 表单大标题
        List<String> titleParams = new ArrayList<>();
        titleParams.add(title);
        if (params.getAreaCode().equals("000000")){
            titleParams.add("未知");
        }else if (params.getAreaCode() != null && params.getAreaCode() != ""){
//            titleParams.add(searchOptionService.queryAreaName(params.getAreaCode()));	TODO 远程调用
        }
        String formTitleName = ExcelTitleUtils.formTitleName(titleParams,params.getStartTime(),params.getEndTime());

        // 表单大标题合并单元格
        List<List<String>> headList = new ArrayList<>();
        List<String> titleList = Arrays.asList("序号", params.getOfficeName()+"ID",params.getOfficeName()+"名称", "操作员活跃数量", "系统活跃数量", "业务活跃数量", "访问量", "受理量", "告警访问量", "失败访问量", "成功率");
        titleList.forEach(s -> {
            List<String> childHeadList = new ArrayList<>();
            childHeadList.add(formTitleName);
            childHeadList.add(s);
            headList.add(childHeadList);
        });

        // 数据整理加上百分号
        resList.forEach(areaOverviewListVo -> {
            areaOverviewListVo.setSuccessRate(areaOverviewListVo.getSuccessRate() == null ? "" : (areaOverviewListVo.getSuccessRate()+ "%"));
//            areaOverviewListVo.setHealthRate(areaOverviewListVo.getHealthRate() == null ? "" : (areaOverviewListVo.getHealthRate()+ "%"));

        });
        //回填序号和处理数据,分情况回填未知
        int index = 1;
        for (HallOverviewListVo vo : resList) {
            vo.setId(index++);
            if (vo.getBusinessHallId() == null || vo.getBusinessHallId().equals("")) {
                vo.setBusinessHallId("-");
            }
            if (vo.getBusinessHallName() == null || vo.getBusinessHallName().equals("")) {
                if (vo.getBusinessHallId() == "-") {
                    vo.setBusinessHallName("-");
                } else {
                    vo.setBusinessHallName("未知");
                }
            }
        }
        ExcelUtil.writeExcel(HallOverviewListVo.class, fileName, "单位总览列表", resList, headList, response);
    }

    /**
     * 操作员总览列表下载
     * @param params 请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "地市监控总览-操作员总览列表下载", notes = "地市监控总览-操作员总览列表下载")
	@ResponseBody
    @PostMapping("/allOperatorOverviewListExport")
    public void queryAllOperatorOverviewListExport(@RequestBody AreaMonitorParams params, HttpServletResponse response) throws IOException, ParseException {

        List<OperatorOverviewListVo> resList = new ArrayList<>();
        try {
            resList = areaMonitorService.queryAllOperatorOverviewListExport(params);
        } catch (Exception e) {
            log.error("所选时间表不存在!但表格需要正常导出.");
        }

        String title = "操作员总览列表";
        // 文件名
        String fileName = title + System.currentTimeMillis();

        // 表单大标题
        List<String> titleParams = new ArrayList<>();
        titleParams.add(title);
        if (params.getAreaName() != null){
            titleParams.add(params.getAreaName());
            if (!params.getBusinessHallId().equals("-1")) {
                titleParams.add(params.getBusinessHallId());
            }
            titleParams.add(params.getBusinessHallName());
        }
        String formTitleName = ExcelTitleUtils.formTitleName(titleParams,params.getStartTime(),params.getEndTime());

        // 表单大标题合并单元格
        List<List<String>> headList = new ArrayList<>();
        List<String> titleList = Arrays.asList("序号", "操作员ID", "姓名", "业务使用数量", "访问量",  "受理量", "告警访问量", "失败访问量","平均办理时长", "成功率");
        titleList.forEach(s -> {
            List<String> childHeadList = new ArrayList<>();
            childHeadList.add(formTitleName);
            childHeadList.add(s);
            headList.add(childHeadList);
        });

        // 数据整理加上百分号
        resList.forEach(areaOverviewListVo -> {
            if (areaOverviewListVo.getAvgVisitTime() == null) {
                areaOverviewListVo.setAvgVisitTime("0.00毫秒");
            } else {
                areaOverviewListVo.setAvgVisitTime(YDateUtil.getMinSecond(getDouble(Double.parseDouble(areaOverviewListVo.getAvgVisitTime()) / 1000)));
            }
            areaOverviewListVo.setSuccessRate(areaOverviewListVo.getSuccessRate() == null ? "" : (areaOverviewListVo.getSuccessRate() + "%"));
        });
        //回填序号和"未知","-"
        int index = 1;
        for (OperatorOverviewListVo vo : resList) {
            vo.setId(index++);
            if (vo.getOperatorId() == null || vo.getOperatorId().equals("")) {
                vo.setOperatorId("-");
            }
            if (vo.getOperatorName() == null || vo.getOperatorName().equals("")) {
                if (vo.getOperatorId() == "-") {
                    vo.setOperatorName("-");
                } else {
                    vo.setOperatorName("未知");
                }
            }
        }
        ExcelUtil.writeExcel(OperatorOverviewListVo.class, fileName, title, resList, headList, response);
    }

    public static Double getDouble(Double allTime) {
        if (allTime == null) { return 0d; }
        return new BigDecimal(allTime).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}
